package com.lovezy.platform.play.service.impl;

import com.github.pagehelper.Page;
import com.lovezy.platform.core.base.enums.StatusEnum;
import com.lovezy.platform.core.base.query.Pager;
import com.lovezy.platform.core.base.service.MapperService;
import com.lovezy.platform.core.exception.ServiceException;
import com.lovezy.platform.play.mapper.PlayMapper;
import com.lovezy.platform.play.model.Play;
import com.lovezy.platform.play.model.PlayExample;
import com.lovezy.platform.play.query.PlayQuery;
import com.lovezy.platform.play.service.PlayService;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 剧本服务
 * Created by jin on 2018/1/24.
 */
@Service
public class PlayServiceImpl extends MapperService<Play,Integer,PlayMapper> implements PlayService{

    @Override
    public Play savePlay(Play play) {
        Date now = new Date();
        play.setGmtCreate(now);
        play.setGmtModify(now);
        play.setStatus(StatusEnum.NORMAL.value());
        play.setModifyId(play.getCreateId());
        mapper.insert(play);
        return play;
    }

    @Override
    public Play editPlay(Play play) {
        Integer playId = play.getPlayId();
        findById(playId, true);
        mapper.updateByPrimaryKeySelective(play);
        return play;
    }

    @Override
    public Play findById(Integer playId, boolean throwIfNotExist) {
        Play play = mapper.selectByPrimaryKey(playId);
        if (throwIfNotExist && play == null) {
            throw new ServiceException("剧本不存在");
        }
        return play;
    }

    @Override
    public void deletePlay(Play play) {
        Integer playId = play.getPlayId();
        Play dbPlay = findById(playId, true);
        dbPlay.setStatus(StatusEnum.DELETED.value());
        dbPlay.setGmtModify(new Date());
        dbPlay.setModifyId(play.getModifyId());
        mapper.updateByPrimaryKeySelective(dbPlay);
    }

    @Override
    public Page<Play> playList(PlayQuery query) {
        PlayExample example = new PlayExample();
        example.setOrderByClause("gmtCreate DESC");
        example.createCriteria()
                .andStatusEqualTo(StatusEnum.NORMAL.value());
        return Pager.doPage(query,() -> {
            mapper.selectByExample(example);
        });
    }

}
